﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using XChipMatlab;
using XChip_Common;
using System.IO;
using System.Configuration;
using XChipTool.Enties;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_DNR_CAL : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        private DevExpress.Utils.WaitDialogForm WaitBeforeLogin = null;
        private addressregisterManager aBll;
        private List<addressregister> XChipDnr_Cal;
        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        public XChip_DNR_CAL()
        {
            InitializeComponent();
        }
        public XChip_DNR_CAL(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipDnr_Cal = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "DNR" || c.Classify == "Common"));

            InitializeComponent();
        }
        private long GetDNRRegister(string nameType)
        {
            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return -1;
            //}
            if (XChipDnr_Cal.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                return SerialSend.ReadRegister(Convert.ToUInt32(XChipDnr_Cal.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), sPortTemp);
            else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
        }
   
       
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }


        private void btn_TuningTips_Click(object sender, EventArgs e)
        {
            //string str = "\t      \t 手动微调噪声模型标定参数,通过调整不同增益下的阈值，标定出不同增益下的噪声波动曲线（噪声曲线呈梯形分布，横轴是局部亮度，纵轴是噪声强度），从而得到该增益下的运动检测阈值Thr；如果像素的 Diff 值大于Thr，则认为该点为运动像素，如果像素的 Diff 值小于 Thr，则认为该点为静止像素。\r\n"
            //  + "\t      \t 注意：x0_node的值需 >0x10，x1_node的值需 <0xef，且（x1_node - x0_node）的值需 >0x40。\r\n";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("DNR_CAL调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    break;
                }
            }
            return listc.ToArray();
        }
        //private void btn_GetISPSetting_Click(object sender, EventArgs e)
        //{

        //    //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
        //    //{
        //    //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
        //    //    return;
        //    //}
        //    isRead = true;
        //    WaitBefore.Start("读取中", "正在加载中", 10);
        //    List<string> NameList = new List<string>();
        //    for (int i = 0; i < XChipDnr_Cal.Count; i++)
        //    {

        //        var type = AppHelper.NameTypeToString(XChipDnr_Cal[i].NameType);
        //        if (NameList.Exists(c => c.ToLower().Contains(type)))
        //        {
        //            continue;
        //        }
        //        //加上单选框的_en
        //        //if (XChipDnr_Cal[i].ControlType == "1")
        //        //{
        //        //    type = XChipDnr_Cal[i].NameType;
        //        //}


        //        try
        //        {
        //            //if (type.Contains("weight_win0"))
        //            //{

        //            //}
        //            var col = Controls_Find(type);
        //            //if (nameType == type) continue;
        //            //nameType = type;
        //            foreach (var item in col)
        //            {
        //                if (item is TextEdit)
        //                {

        //                    var nList = XChipDnr_Cal.Where(c => c.NameType.ToLower().Contains(type)).ToList();
        //                    if (nList.Count == 1)
        //                    {
        //                        var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
        //                        item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
        //                    }
        //                    else {
        //                        string Val = string.Empty;
        //                        //这里默认为是有多个寄存器  一个文本框的情况进行处理
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
        //                        {
        //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
        //                        }
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
        //                        {
        //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
        //                        }
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
        //                        {
        //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
        //                        }
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
        //                        {
        //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
        //                        }
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_m3")))
        //                        {
        //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m3")).Address, 16), sPortTemp).ToString("X2");
        //                        }
        //                        if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
        //                        {
        //                            if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
        //                            {
        //                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
        //                            }
        //                            else
        //                            {
        //                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
        //                            }
        //                        }

        //                        item.Text = Val;
        //                    }
        //                        //item.Text = tempU.ToString("X");
        //                }
        //                else if (item is CheckEdit)
        //                {
        //                    var nList = XChipDnr_Cal.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
        //                    if (nList.Count == 1)
        //                    {
        //                        var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
        //                        (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
        //                    }
        //                }

        //                NameList.Add(type);
        //            }


        //        }
        //        catch (Exception)
        //        {
        //            continue;
        //        }
        //    }
        //    WaitBefore.Close();
        //    isRead = false;
        //}

        private async void btn_GetISPSetting_Click(object sender, EventArgs e)
        {
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);

            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;

            try
            {
                List<string> NameList = new List<string>();

                for (int i = 0; i < XChipDnr_Cal.Count; i++)
                {
                    var type = AppHelper.NameTypeToString(XChipDnr_Cal[i].NameType);
                    if (NameList.Exists(c => c.ToLower().Contains(type)))
                    {
                        continue;
                    }

                    try
                    {
                        var col = Controls_Find(type);
                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                var nList = XChipDnr_Cal.Where(c => c.NameType.ToLower().Contains(type)).ToList();
                                if (nList.Count == 1)
                                {
                                    // 单个寄存器读取
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                     await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                                   
                                }
                                else
                                {
                                    // 多个寄存器组合读取
                                    totalRegisterCount += nList.Count;
                                    await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                                    
                                }
                            }
                            else if (item is CheckEdit)
                            {
                                var nList = XChipDnr_Cal.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                                if (nList.Count == 1)
                                {
                                    var address = nList[0].Address;
                                    totalRegisterCount++;
                                     await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                                   
                                }
                            }

                            NameList.Add(type);

                            // 在控件之间添加延迟
                            await Task.Delay(10);
                        }

                        // 在类型之间添加延迟
                        await Task.Delay(10);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[ADBForm] 处理类型 {type} 时发生异常: {ex.Message}");
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"读取ISP设置时发生错误: {ex.Message}");
            }
            finally
            {
                WaitBefore.Close();
                isRead = false;

                // 打印运行统计信息
                var endTime = DateTime.Now;
                var elapsedTime = endTime - startTime;
                Console.WriteLine($"[ADBForm] 读取完成 - 总耗时: {elapsedTime.TotalSeconds:F2}秒");
                Console.WriteLine($"[ADBForm] 寄存器统计 - 总数: {totalRegisterCount}");

                // 更新状态栏显示统计信息
                //UpdateStatus($"读取完成 - 耗时:{elapsedTime.TotalSeconds:F1}秒, 成功:{successfulRegisterCount}/{totalRegisterCount}");
            }
        }
        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read",500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read",500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read",500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }



        /// <summary>
        /// send
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSend_Click(object sender, EventArgs e)
        {
            if (!JudgeNr3dTxt()) return;
           // var noise_x_node_list =new double[9, 2]{ { Convert.ToInt32(x1_node_1x.Text, 16), Convert.ToInt32(x2_node_1x.Text, 16) },
           //{ Convert.ToInt32(x1_node_2x.Text, 16), Convert.ToInt32(x2_node_2x.Text, 16) },
           //{ Convert.ToInt32(x1_node_4x.Text, 16), Convert.ToInt32(x2_node_4x.Text, 16) },
           //{ Convert.ToInt32(x1_node_8x.Text, 16), Convert.ToInt32(x2_node_8x.Text, 16) },
           //{ Convert.ToInt32(x1_node_16x.Text, 16), Convert.ToInt32(x2_node_16x.Text, 16) },
           //{ Convert.ToInt32(x1_node_32x.Text, 16), Convert.ToInt32(x2_node_32x.Text, 16) },
           //{ Convert.ToInt32(x1_node_64x.Text, 16), Convert.ToInt32(x2_node_64x.Text, 16) },
           //{ Convert.ToInt32(x1_node_128x.Text, 16), Convert.ToInt32(x2_node_128x.Text, 16) },
           // { Convert.ToInt32(x1_node_256x.Text, 16), Convert.ToInt32(x2_node_256x.Text, 16)}};
            var noise_x_node_list = new decimal[]{  Convert.ToInt32(x0_node_1x.Text, 16), Convert.ToInt32(x1_node_1x.Text, 16) ,
            Convert.ToInt32(x0_node_2x.Text, 16), Convert.ToInt32(x1_node_2x.Text, 16) ,
            Convert.ToInt32(x0_node_4x.Text, 16), Convert.ToInt32(x1_node_4x.Text, 16),
            Convert.ToInt32(x0_node_8x.Text, 16), Convert.ToInt32(x1_node_8x.Text, 16) ,
            Convert.ToInt32(x0_node_16x.Text, 16), Convert.ToInt32(x1_node_16x.Text, 16) ,
            Convert.ToInt32(x0_node_32x.Text, 16), Convert.ToInt32(x1_node_32x.Text, 16) ,
            Convert.ToInt32(x0_node_64x.Text, 16), Convert.ToInt32(x1_node_64x.Text, 16) ,
            Convert.ToInt32(x0_node_128x.Text, 16), Convert.ToInt32(x1_node_128x.Text, 16) ,
            Convert.ToInt32(x0_node_256x.Text, 16), Convert.ToInt32(x1_node_256x.Text, 16)};
            var offset_lf = new decimal[] { Convert.ToInt32(offset_lt_1x.Text, 16),
            Convert.ToInt32(offset_lt_2x.Text, 16),
            Convert.ToInt32(offset_lt_4x.Text, 16),
            Convert.ToInt32(offset_lt_8x.Text, 16),
            Convert.ToInt32(offset_lt_16x.Text, 16),
            Convert.ToInt32(offset_lt_32x.Text, 16),
            Convert.ToInt32(offset_lt_64x.Text, 16),
            Convert.ToInt32(offset_lt_128x.Text, 16),
            Convert.ToInt32(offset_lt_256x.Text, 16),};
            var limit_up = new decimal[] { Convert.ToInt32(limit_up_1x.Text, 16),
            Convert.ToInt32(limit_up_2x.Text, 16),
            Convert.ToInt32(limit_up_4x.Text, 16),
            Convert.ToInt32(limit_up_8x.Text, 16),
            Convert.ToInt32(limit_up_16x.Text, 16),
            Convert.ToInt32(limit_up_32x.Text, 16),
            Convert.ToInt32(limit_up_64x.Text, 16),
            Convert.ToInt32(limit_up_128x.Text, 16),
            Convert.ToInt32(limit_up_256x.Text, 16),};
            var offset_rt = new decimal[] { Convert.ToInt32(offset_rt_1x.Text, 16),
            Convert.ToInt32(offset_rt_2x.Text, 16),
            Convert.ToInt32(offset_rt_4x.Text, 16),
            Convert.ToInt32(offset_rt_8x.Text, 16),
            Convert.ToInt32(offset_rt_16x.Text, 16),
            Convert.ToInt32(offset_rt_32x.Text, 16),
            Convert.ToInt32(offset_rt_64x.Text, 16),
            Convert.ToInt32(offset_rt_128x.Text, 16),
            Convert.ToInt32(offset_rt_256x.Text, 16),};



            decimal[] slope_lf = new decimal[9];
            decimal[] slope_rt = new decimal[9];
            decimal[] offset_lf_norm = new decimal[offset_lf.Length];
            decimal[] limit_up_norm = new decimal[limit_up.Length];
            for (int i = 0; i < offset_lf.Length; i++)
            {
                offset_lf_norm[i] = ((int)offset_lf[i] << 6) + 32;
            }
            for (int i = 0; i < limit_up.Length; i++)
            {
                limit_up_norm[i] = ((int)limit_up[i] << 8) + 128;

            }
            decimal[] offset_rt_norm = offset_rt;
            decimal[] slope, y_nos;
            YedgeHelp yh = new YedgeHelp();
            for (int i = 0; i < 9; i++)
            {
                decimal[] noise_x_node = new decimal[] { noise_x_node_list[i * 2], noise_x_node_list[i * 2 + 1] };
                decimal[] noise_y_node = new decimal[] { offset_lf_norm[i], limit_up_norm[i], offset_rt_norm[i] };
                yh.noise_profile(noise_x_node, noise_y_node, out y_nos, out slope);
                slope_lf[i] = slope[0];
                slope_rt[i] = slope[1];
            }
            for (int i = 0; i < slope_lf.Length; i++)
            {
                slope_lf[i] = ((int)(slope_lf[i] + 2)) >> 2;
            }
            for (int i = 0; i < slope_rt.Length; i++)
            {
                slope_rt[i] = ((int)(slope_rt[i] + 2)) >> 2;
            }
            List<String> sbList = new List<string>();
            List<ISPReg> regList = new List<ISPReg>();
            regList.Add(new ISPReg() { addr = Convert.ToUInt32("fffd", 16), value = Convert.ToUInt32("80", 16) });
            regList.Add(new ISPReg() { addr = Convert.ToUInt32("fffe", 16), value = Convert.ToUInt32("30", 16) });
            regList.AddRange(yh.para_to_reg(slope_lf, 13, "3c10"));
            regList.AddRange(yh.para_to_reg(offset_lf, 14, "3c22"));
            regList.AddRange(yh.para_to_reg(slope_rt, 14, "3cba"));
            regList.AddRange(yh.para_to_reg(offset_rt, 14, "3ccc"));
            regList.AddRange(yh.para_to_reg(limit_up, 14, "3cde"));



            Task.Run(() =>
            {
                WaitBeforeLogin = new DevExpress.Utils.WaitDialogForm("请稍候...", "正在加载DNR_CAL应用系统");
                WaitBeforeLogin.StartPosition = FormStartPosition.CenterParent;
                Application.Run(WaitBeforeLogin);
            });

            try
            {
                uint addrBHigh = 0x80;
                uint addrMid = 0;

                // 使用List来收集所有需要写入的寄存器
                var writeOperations = new List<Func<Task<bool>>>();

                // 收集regList的写入操作
                foreach (var item in regList)
                {
                    if (item.addr == 0xffff)
                        continue;
                    else if (item.addr == 0xfffd)
                    {
                        addrBHigh = item.value;
                        continue;
                    }
                    else if (item.addr == 0xfffe)
                    {
                        addrMid = item.value;
                        continue;
                    }

                    var address = ((addrBHigh << 24) + (addrMid << 16) + item.addr);
                    var value = item.value;

                    // 将写入操作添加到列表
                    writeOperations.Add(async () =>
                    {
                        return await WriteRegisterAsync(address.ToString("X"), value.ToString("X"));
                    });
                }

                // 顺序执行所有写入操作
                foreach (var writeOp in writeOperations)
                {
                    bool success = await writeOp();
                    if (!success)
                    {
                        Console.WriteLine($"[ADBForm] 写入操作失败，但继续执行后续操作");
                    }

                    // 可选：在写入操作之间添加小延迟
                    await Task.Delay(5);
                }

                // 收集x0_node系列的写入操作
                var x0WriteOperations = new List<Func<Task>>();

                // 使用字典来简化重复的代码
                var x0Nodes = new[]
                {
            x0_node_1x, x0_node_2x, x0_node_4x, x0_node_8x,
            x0_node_16x, x0_node_32x, x0_node_64x, x0_node_128x, x0_node_256x
        };

                foreach (var node in x0Nodes)
                {
                    if (XChipDnr_Cal.Exists(c => c.NameType.ToLower() == node.Name.ToLower()))
                    {
                        var model = XChipDnr_Cal.Find(c => c.NameType.ToLower() == node.Name.ToLower());
                        var val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, node.Text);

                        x0WriteOperations.Add(async () =>
                        {
                            await SetDNRRegisterAsync(model, val);
                        });
                    }
                }

                // 顺序执行x0_node写入操作
                foreach (var writeOp in x0WriteOperations)
                {
                    await writeOp();
                    await Task.Delay(5); // 小延迟
                }

                // 收集x1_node系列的写入操作
                var x1WriteOperations = new List<Func<Task>>();

                var x1Nodes = new[]
                {
            x1_node_1x, x1_node_2x, x1_node_4x, x1_node_8x,
            x1_node_16x, x1_node_32x, x1_node_64x, x1_node_128x, x1_node_256x
        };

                foreach (var node in x1Nodes)
                {
                    if (XChipDnr_Cal.Exists(c => c.NameType.ToLower() == node.Name.ToLower()))
                    {
                        var model = XChipDnr_Cal.Find(c => c.NameType.ToLower() == node.Name.ToLower());
                        var val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, node.Text);

                        x1WriteOperations.Add(async () =>
                        {
                            await SetDNRRegisterAsync(model, val);
                        });
                    }
                }

                // 顺序执行x1_node写入操作
                foreach (var writeOp in x1WriteOperations)
                {
                    await writeOp();
                    await Task.Delay(5); // 小延迟
                }

                btnSend.Invoke((EventHandler)delegate { btnSend.Enabled = true; });
            }
            catch (Exception ex)
            {
                btnSend.Invoke((EventHandler)delegate { btnSend.Enabled = true; });
                DevExpress.XtraEditors.XtraMessageBox.Show("错误信息：" + ex.Message.ToString());
            }
            finally
            {
                WaitBeforeLogin.Invoke((EventHandler)delegate { WaitBeforeLogin.Close(); });
            }
        }

        /// <summary>
        /// 异步版本的SetDNRRegister方法
        /// </summary>
        private async Task SetDNRRegisterAsync(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetDNRRegisterAsync 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }
        }

        private async void SetDNRRegister(addressregister model, ulong add, bool isCheck = true)
        {
            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
            //    return;
            //}
            if (isRead) return;
            //if (IsUsbOpen)
            //{
            //    if (null != BinHelp.usbList)
            //    {
            //        uint pVule = 0x0;
            //        var isbool = false;
            //        if (IntPtr.Size == 8)
            //        {
            //            isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
            //            SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


            //        }
            //        else
            //        {
            //            isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
            //            SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
            //        }
            //        var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
            //        var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

            //        BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
            //    }
            //}
            //else if (m_open)
            //{

            //}
            //else
            //{
            //    if (!sPortTemp.IsOpen)
            //    {
            //        DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //        return;
            //    }

            //    if (null != BinHelp.lspList)
            //    { //编写Bin更新数据
            //        var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
            //        BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
            //    }
            //}


            //SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));
        }

        bool JudgeNr3dTxt()
        {

            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return false;
            //}


            if (string.IsNullOrEmpty(offset_lt_1x.Text)||
                string.IsNullOrEmpty(offset_lt_2x.Text)||
                string.IsNullOrEmpty(offset_lt_4x.Text)||
                string.IsNullOrEmpty(offset_lt_8x.Text)||
                string.IsNullOrEmpty(offset_lt_16x.Text)||
                string.IsNullOrEmpty(offset_lt_32x.Text)||
                string.IsNullOrEmpty(offset_lt_64x.Text)||
                string.IsNullOrEmpty(offset_lt_128x.Text)||
                string.IsNullOrEmpty(offset_lt_256x.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Offset_Lt  参数缺省！");
                return false;
            }

            if (string.IsNullOrEmpty(offset_rt_1x.Text) ||
                string.IsNullOrEmpty(offset_rt_2x.Text) ||
                string.IsNullOrEmpty(offset_rt_4x.Text) ||
                string.IsNullOrEmpty(offset_rt_8x.Text) ||
                string.IsNullOrEmpty(offset_rt_16x.Text) ||
                string.IsNullOrEmpty(offset_rt_32x.Text) ||
                string.IsNullOrEmpty(offset_rt_64x.Text) ||
                string.IsNullOrEmpty(offset_rt_128x.Text) ||
                string.IsNullOrEmpty(offset_rt_256x.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Offset_Rt  参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(limit_up_1x.Text) ||
                string.IsNullOrEmpty(limit_up_2x.Text) ||
                string.IsNullOrEmpty(limit_up_4x.Text) ||
                string.IsNullOrEmpty(limit_up_8x.Text) ||
                string.IsNullOrEmpty(limit_up_16x.Text) ||
                string.IsNullOrEmpty(limit_up_32x.Text) ||
                string.IsNullOrEmpty(limit_up_64x.Text) ||
                string.IsNullOrEmpty(limit_up_128x.Text) ||
                string.IsNullOrEmpty(limit_up_256x.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Limit_Up  参数缺省！");
                return false;
            }
            if (string.IsNullOrEmpty(x0_node_1x.Text) ||
                string.IsNullOrEmpty(x0_node_2x.Text) ||
                string.IsNullOrEmpty(x0_node_4x.Text) ||
                string.IsNullOrEmpty(x0_node_8x.Text) ||
                string.IsNullOrEmpty(x0_node_16x.Text) ||
                string.IsNullOrEmpty(x0_node_32x.Text) ||
                string.IsNullOrEmpty(x0_node_64x.Text) ||
                string.IsNullOrEmpty(x0_node_128x.Text) ||
                string.IsNullOrEmpty(x0_node_256x.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("X1_Node  参数缺省！");
                return false;
            }
            if (Convert.ToInt32(x0_node_1x.Text,16)<16 ||
                Convert.ToInt32(x0_node_2x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_4x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_8x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_16x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_32x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_64x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_128x.Text, 16) < 16 ||
                Convert.ToInt32(x0_node_256x.Text, 16) < 16)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("X0_Node  参数必须大于等于0x10");
                return false;
            }

            if (string.IsNullOrEmpty(x1_node_1x.Text) ||
                string.IsNullOrEmpty(x1_node_2x.Text) ||
                string.IsNullOrEmpty(x1_node_4x.Text) ||
                string.IsNullOrEmpty(x1_node_8x.Text) ||
                string.IsNullOrEmpty(x1_node_16x.Text) ||
                string.IsNullOrEmpty(x1_node_32x.Text) ||
                string.IsNullOrEmpty(x1_node_64x.Text) ||
                string.IsNullOrEmpty(x1_node_128x.Text) ||
                string.IsNullOrEmpty(x1_node_256x.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("X1_Node  参数缺省！");
                return false;
            }
            if (Convert.ToInt32(x1_node_1x.Text, 16)>239 ||
                Convert.ToInt32(x1_node_2x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_4x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_8x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_16x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_32x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_64x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_128x.Text, 16) > 239 ||
                Convert.ToInt32(x1_node_256x.Text, 16) > 239)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("X1_Node  参数必须小于0xEF");
                return false;
            }
            if (Convert.ToInt32(x1_node_1x.Text, 16)- Convert.ToInt32(x0_node_1x.Text,16)<64||
                Convert.ToInt32(x1_node_2x.Text, 16)- Convert.ToInt32(x0_node_2x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_4x.Text, 16)- Convert.ToInt32(x0_node_4x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_8x.Text, 16)- Convert.ToInt32(x0_node_8x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_16x.Text, 16)-Convert.ToInt32(x0_node_16x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_32x.Text, 16)-Convert.ToInt32(x0_node_32x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_64x.Text, 16)-Convert.ToInt32(x0_node_64x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_128x.Text, 16)-Convert.ToInt32(x0_node_128x.Text, 16) < 64 ||
                Convert.ToInt32(x1_node_256x.Text, 16)-Convert.ToInt32(x0_node_256x.Text, 16) < 64)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("X1_Node 减 X0_Node 参数必须大于0x40");
                return false;
            }

            return true;
        }

        private void XChip_DNR_CAL_Load(object sender, EventArgs e)
        {
            //if (ConfigurationManager.AppSettings["xcEdition"] == "1")
            //{
            //    btn_GetISPSetting.Text = "获取参数";
            //    btn_TuningTips.Text = "调试指南";
            //    btnSend.Text = "发送";
            //}
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {
                for (int i = 0; i < XChipDnr_Cal.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipDnr_Cal[i].NameType);
                    //加上单选框的_en
                    if (XChipDnr_Cal[i].ControlType == "1")
                    {
                        type = XChipDnr_Cal[i].NameType;
                    }
                    try
                    {
                        var col = this.Controls.Find(type, true);


                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                //声明一个SuerToolTip
                                DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                //声明一个ToolTipTitleItem,保存标题
                                DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                String tooltips = "";

                                if (!string.IsNullOrEmpty(XChipDnr_Cal[i].Bit_Wide))
                                {
                                    tooltips += $"位宽={XChipDnr_Cal[i].Bit_Wide}";
                                }
                                if (!string.IsNullOrEmpty(XChipDnr_Cal[i].Bit_Accuracy))
                                {
                                    tooltips += $"|精度={XChipDnr_Cal[i].Bit_Accuracy}";
                                }
                                //设置标题文字
                                toolTipTitleItem.Text = tooltips;
                                //把标题添加到SuerToolTip
                                graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                //指定控件的SuperTip
                                ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                //正则判断
                                ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipDnr_Cal[i].Bits, XChipDnr_Cal[i].Bit_Wide, XChipDnr_Cal.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            });
            });
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_DNR_CAL_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList(c => c.Module == "AWB");
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "3D DNR").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {
                        if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                    var sb = XChipHelp.ReadParameterExportExpand(tempList, "80", patchList, sPortTemp);
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());

                }
                WaitBefore.Close();
                DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            }
        }
    }           
}               
                